package com.application.controller;


import com.application.domain.Activity;
import com.application.domain.sort;
import com.application.service.ActivityService;
import com.application.service.SortService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/sorts")
@Api("主页分块")
public class SortController {

    @Resource
    SortService sortService;
    @Resource
    ActivityService activityService;


    @GetMapping
    @ApiOperation("查询全部信息")
    public Result getAll(){
        List<sort> list = sortService.getAll();
        String mes = list !=null? "查询成功":"查询失败，请重新尝试";
        int code = list!=null ? Code.SELECT_OK:Code.SELECT_ERR;
        return new Result(code,list,mes);
    }

    @PostMapping("/commit")
    @ApiOperation("保存图片地址到数据库")
    public Result download(@RequestBody sort sort){
        sort sort1 = sortService.getById(sort.getId());
        int column=0;

        if(sort1!=null){
            column=sortService.update(sort);
        }else{
            column=sortService.insert(sort);
        }

        int code = column!=0?Code.UPDATE_OK:Code.UPDATE_ERR;
        String mes = column!=0?"更新成功":"更新失败，请重新尝试";

        return new Result(code,column,mes);
    }

    @DeleteMapping
    @ApiOperation("删除功能")
    public Result deleted(@RequestParam String id){

        int deleteById = sortService.deleteById(id);

        int code = deleteById!=0?Code.DELETE_OK:Code.DELETE_ERR;
        String mes = deleteById!=0?"删除成功":"删除失败，请重新尝试";
        return new Result(code,deleteById,mes);
    }


    @ApiOperation("插入功能")
    @PostMapping
    public Result save(@RequestBody sort sort){
        int insert = sortService.insert(sort);

        int code = insert!=0?Code.SAVE_OK:Code.SAVE_ERR;
        String mes= insert!=0?"保存数据成功":"保存数据失败，请重新尝试";

        return new Result(code,insert,mes);
    }


    @ApiOperation("根据类别查询活动")
    @GetMapping("/check")
    public Result selectByName(@RequestParam String name){
        List<Activity> activities = activityService.selectByName(name);
        String mes = activities!=null ? "查询成功":"没有活动";
        int code =  activities!=null ? Code.SELECT_OK:Code.SELECT_ERR;
        return new Result(code,activities,mes);
    }
}
